package com.zjx.mhxykey.util;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.util.Log;

/**
 * Bitmap 抠图工具类
 * 提供多种抠图方式：矩形区域、圆形、路径抠图、颜色抠图等
 */
public class BitmapCutoutUtils {
    private static final String TAG = "BitmapCutoutUtils";

    /**
     * 从Bitmap中截取矩形区域
     * @param source 源Bitmap
     * @param rect 要截取的区域（基于源Bitmap坐标系）
     * @return 截取后的Bitmap，失败返回null
     */
    public static Bitmap cutRect(Bitmap source, Rect rect) {
        if (source == null || rect == null) {
            Log.w(TAG, "cutRect: 参数不能为null");
            return null;
        }

        try {
            // 确保区域在Bitmap范围内
            Rect validRect = new Rect(
                    Math.max(0, rect.left),
                    Math.max(0, rect.top),
                    Math.min(source.getWidth(), rect.right),
                    Math.min(source.getHeight(), rect.bottom)
            );

            if (validRect.width() <= 0 || validRect.height() <= 0) {
                Log.w(TAG, "cutRect: 无效的矩形区域");
                return null;
            }

            return Bitmap.createBitmap(
                    source,
                    validRect.left,
                    validRect.top,
                    validRect.width(),
                    validRect.height()
            );
        } catch (Exception e) {
            Log.e(TAG, "cutRect: 截取失败", e);
            return null;
        }
    }

    /**
     * 从Bitmap中截取圆形区域
     * @param source 源Bitmap
     * @param centerX 圆心X坐标
     * @param centerY 圆心Y坐标
     * @param radius 半径
     * @return 圆形区域的Bitmap，背景透明
     */
    public static Bitmap cutCircle(Bitmap source, float centerX, float centerY, float radius) {
        if (source == null) {
            Log.w(TAG, "cutCircle: 源Bitmap不能为null");
            return null;
        }

        try {
            // 创建目标Bitmap
            Bitmap output = Bitmap.createBitmap(
                    source.getWidth(),
                    source.getHeight(),
                    Bitmap.Config.ARGB_8888
            );
            Canvas canvas = new Canvas(output);

            // 绘制圆形遮罩
            Path path = new Path();
            path.addCircle(centerX, centerY, radius, Path.Direction.CCW);
            canvas.clipPath(path);

            // 绘制源图像
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            canvas.drawBitmap(source, 0, 0, paint);

            return output;
        } catch (Exception e) {
            Log.e(TAG, "cutCircle: 圆形抠图失败", e);
            return null;
        }
    }

    /**
     * 根据路径抠图
     * @param source 源Bitmap
     * @param path 抠图路径
     * @return 路径内的Bitmap，背景透明
     */
    public static Bitmap cutPath(Bitmap source, Path path) {
        if (source == null || path == null) {
            Log.w(TAG, "cutPath: 参数不能为null");
            return null;
        }

        try {
            Bitmap output = Bitmap.createBitmap(
                    source.getWidth(),
                    source.getHeight(),
                    Bitmap.Config.ARGB_8888
            );
            Canvas canvas = new Canvas(output);

            // 应用路径裁剪
            canvas.clipPath(path);
            canvas.drawBitmap(source, 0, 0, new Paint(Paint.ANTI_ALIAS_FLAG));

            return output;
        } catch (Exception e) {
            Log.e(TAG, "cutPath: 路径抠图失败", e);
            return null;
        }
    }

    /**
     * 去除背景色（基于颜色相似度）
     * @param source 源Bitmap
     * @param bgColor 要移除的背景色
     * @param tolerance 容差范围(0-255)
     * @return 去除背景后的Bitmap，背景透明
     */
    public static Bitmap removeBackground(Bitmap source, int bgColor, int tolerance) {
        if (source == null) {
            Log.w(TAG, "removeBackground: 源Bitmap不能为null");
            return null;
        }

        try {
            int width = source.getWidth();
            int height = source.getHeight();
            Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

            int bgR = Color.red(bgColor);
            int bgG = Color.green(bgColor);
            int bgB = Color.blue(bgColor);

            // 遍历所有像素
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int pixel = source.getPixel(x, y);
                    int r = Color.red(pixel);
                    int g = Color.green(pixel);
                    int b = Color.blue(pixel);

                    // 计算颜色距离
                    double distance = Math.sqrt(
                            Math.pow(r - bgR, 2) +
                                    Math.pow(g - bgG, 2) +
                                    Math.pow(b - bgB, 2)
                    );

                    // 根据容差决定是否透明
                    if (distance <= tolerance) {
                        output.setPixel(x, y, Color.TRANSPARENT);
                    } else {
                        output.setPixel(x, y, pixel);
                    }
                }
            }

            return output;
        } catch (Exception e) {
            Log.e(TAG, "removeBackground: 去除背景失败", e);
            return null;
        }
    }

    /**
     * 保留指定颜色范围内的像素
     * @param source 源Bitmap
     * @param targetColor 目标颜色
     * @param hueTolerance 色相容差(0-180)
     * @param satTolerance 饱和度容差(0-1)
     * @param valTolerance 明度容差(0-1)
     * @return 处理后的Bitmap，非目标颜色区域透明
     */
    public static Bitmap keepColorRange(Bitmap source, int targetColor,
                                        float hueTolerance, float satTolerance, float valTolerance) {
        if (source == null) {
            Log.w(TAG, "keepColorRange: 源Bitmap不能为null");
            return null;
        }

        try {
            int width = source.getWidth();
            int height = source.getHeight();
            Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

            float[] targetHsv = new float[3];
            Color.colorToHSV(targetColor, targetHsv);

            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int pixel = source.getPixel(x, y);
                    float[] hsv = new float[3];
                    Color.colorToHSV(pixel, hsv);

                    // 检查HSV值是否在容差范围内
                    boolean hueInRange = Math.abs(hsv[0] - targetHsv[0]) <= hueTolerance;
                    boolean satInRange = Math.abs(hsv[1] - targetHsv[1]) <= satTolerance;
                    boolean valInRange = Math.abs(hsv[2] - targetHsv[2]) <= valTolerance;

                    if (hueInRange && satInRange && valInRange) {
                        output.setPixel(x, y, pixel);
                    } else {
                        output.setPixel(x, y, Color.TRANSPARENT);
                    }
                }
            }

            return output;
        } catch (Exception e) {
            Log.e(TAG, "keepColorRange: 颜色保留失败", e);
            return null;
        }
    }
}